<?php

namespace app\common\services;

use app\common\repositories\system\SystemEmailConfigRepository;
use app\common\repositories\system\SystemEmailRepository;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use support\Container;

class EmailService{

    public function email($toemail,$title = '',$content = ''){
        try{
            $config = Container::make(SystemEmailConfigRepository::class)->getDefaultEmailConfig();
            if(empty($config)) return false;
            $mail = new PHPMailer();
            $mail->isSMTP();
            $mail->CharSet = 'utf8';
            $mail->Host = $config->host;
            $mail->SMTPAuth = true;
            $mail->Username = $config->username;
            $mail->Password = $config->password;
            $mail->SMTPSecure = $config->type;
            $mail->Port = $config->port;
            $mail->setFrom($config->username, $config->name);
            $mail->addAddress($toemail,'');
            $mail->addReplyTo($config->username, $config->name);
            $mail->Subject = $title;
            $mail->Body = $content;
    
            $flag = true;
            if ($mail->send()) {
                $flag = true;
            } else {
                $flag = false;
            }
            Container::make(SystemEmailRepository::class)->createOneSystemEmail($toemail,$title,$content,$flag ? 1 : 0);
            return $flag;

        }catch(Exception $e){
            return false;
        }

    }

}
